package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.heima.behavior.service.CollectionService;
import com.heima.common.util.RequestContextUtil;
import com.heima.model.behavior.dtos.CollectionDto;
import com.heima.model.behavior.pojos.CollectionDoc;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


@Service
public class CollectionServiceImpl implements CollectionService {
    /**
     * 收藏
     * @param dto
     * @return
     */
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult collectionBehavior(CollectionDto dto) {
        int userId = RequestContextUtil.get("id");
        Query query = Query.query(Criteria.where("articleId").is(dto.getEntryId()).and("userId").is(userId));
        long count = mongoTemplate.count(query, CollectionDoc.class);
        if (count <= 0) {
            CollectionDoc doc = new CollectionDoc(IdWorker.getId(), userId, dto.getEntryId());
            mongoTemplate.save(doc);
            System.out.println("收藏成功");
            return ResponseResult.okResult();
        } else {
            mongoTemplate.remove(query, CollectionDoc.class);
            System.out.println("取消收藏成功");
            return ResponseResult.okResult();
        }
    }

    /**
     * 数据回显——收藏
     * @param userId
     * @param
     * @return
     */
    @Override
    public Boolean isCollection(int userId, Long articleId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("articleId").is(articleId));
        long count = mongoTemplate.count(query, CollectionDoc.class);
        return count > 0;
    }

}
